package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatusCode;
import cn.tedu._05weibo.mappers.WeiboMapper;
import cn.tedu._05weibo.pojo.dto.WeiboDTO;
import cn.tedu._05weibo.pojo.entity.Weibo;
import cn.tedu._05weibo.pojo.vo.UserVO;
import cn.tedu._05weibo.pojo.vo.WeiboDetailVO;
import cn.tedu._05weibo.pojo.vo.WeiboIndexVO;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
@Validated
@Api(tags = "02.微博模块")
@Slf4j
@RestController
@RequestMapping("/v1/weibo/")
public class WeiboController {
    @Autowired
    private WeiboMapper weiboMapper;

    /**
     * 1.发布微博功能
     */
    @ApiOperation("发布微博")
    @PostMapping("insert")
    public JsonResult insert(@RequestBody WeiboDTO weiboDTO, @ApiIgnore HttpSession session) {
        /*
            1.校验用户登录状态
                1.1 未登录：return 2;
                1.2 登录：插入数据，return 1;
         */
        //System.out.println("weiboDTO = " + weiboDTO);
        log.debug("weiboDTO = " + weiboDTO);
        UserVO userVO = (UserVO) session.getAttribute("user");
//        if (userVO == null) {
//            return new JsonResult(StatusCode.NOT_LOGIN);
//        }
        Weibo weibo = new Weibo();
        BeanUtils.copyProperties(weiboDTO, weibo);
        weibo.setCreated(new Date());
        //获取用户Id
        weibo.setUserId(userVO.getId());
        weiboMapper.insert(weibo);
        return JsonResult.ok(weibo);
    }

    /**
     * 2.微博首页功能
     */
    @ApiOperation("微博首页")
    @GetMapping("selectIndex")
    public JsonResult index() {
        List<WeiboIndexVO> weiboIndexVOS = weiboMapper.selectIndex();
        return JsonResult.ok(weiboIndexVOS);
    }

    /**
     * 3.微博详情页面功能
     */
    @ApiOperation("微博详情页")
    @GetMapping("selectById")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "微博ID", required = true,
                    dataType = "Long"),
            @ApiImplicitParam(name = "username", value = "用户名", required = true,
                    dataType = "String")
    })
    public JsonResult selectById(@Range(min = 200,max = 300,message = "微博ID必须在200-300之间") @RequestParam Long id, String username) {
        //手动抛出异常
        if(id<0){
            throw new IllegalArgumentException("ID值不能小于0");
        }
        WeiboDetailVO weiboDetailVO = weiboMapper.selectById(id);
        return JsonResult.ok(weiboDetailVO);
    }
}
